package com.ruoyi.app.controller.order.service.impl;

import com.ruoyi.app.common.utils.IdWorker;
import com.ruoyi.app.controller.marketing.entity.MemberCouponSearchVO;
import com.ruoyi.app.controller.marketing.entity.MemberCouponVO;
import com.ruoyi.app.controller.member.mapper.*;
import com.ruoyi.app.controller.member.service.IMemberCouponService;
import com.ruoyi.app.controller.order.entity.PetrolDiscountBO;
import com.ruoyi.app.controller.order.entity.ShopPetrolOrderConfirmVO;
import com.ruoyi.app.controller.order.mapper.IShopPetrolOrderMapper;
import com.ruoyi.app.controller.order.service.IShopPetrolOrderService;
import com.ruoyi.app.controller.product.mapper.IProductMapper;
import com.ruoyi.app.controller.product.mapper.IShopProductAttributeMapper;
import com.ruoyi.app.controller.product.mapper.IShopProductConfigMapper;
import com.ruoyi.app.controller.shop.mapper.IShopMapper;
import com.ruoyi.app.framework.manager.AsyncManager;
import com.ruoyi.app.framework.manager.factory.ApiAsyncFactory;
import com.ruoyi.common.constant.*;
import com.ruoyi.common.entity.DO.member.MemberBalanceRecordDO;
import com.ruoyi.common.entity.DO.member.MemberCreditRecordDO;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.DO.order.ShopPetrolOrderDO;
import com.ruoyi.common.entity.DO.product.ShopProductConfigDO;
import com.ruoyi.common.entity.VO.PayVO;
import com.ruoyi.common.entity.VO.member.MemberVO;
import com.ruoyi.common.entity.VO.member.MemberVipBenefitVO;
import com.ruoyi.common.entity.VO.order.ShopOrderSearchVO;
import com.ruoyi.common.entity.VO.product.PetrolProductVO;
import com.ruoyi.common.entity.VO.shop.ShopProductSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopVO;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;

@Service("IShopPetrolOrderService")
@Slf4j
public class ShopPetrolOrderServiceImpl implements IShopPetrolOrderService {

    @Resource
    private IMemberCouponService memberCouponService;

    @Resource
    private IShopPetrolOrderMapper shopPetrolOrderMapper;

    @Resource
    private IProductMapper productMapper;

    @Resource
    private IShopMapper shopMapper;

    @Resource
    private IMemberMapper memberMapper;

    @Resource
    private IMemberBalanceRecordMapper memberBalanceRecordMapper;

    @Resource
    private IMemberCreditRecordMapper memberCreditRecordMapper;

    @Resource
    private IMemberVipBenefitMapper memberVipBenefitMapper;

    @Resource
    private IShopProductAttributeMapper shopProductAttributeMapper;

    @Resource
    private IShopProductConfigMapper shopProductConfigMapper;

    @Resource
    private IMemberVipBenefitExtMapper memberVipBenefitExtMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Synchronized
    public String create(ShopPetrolOrderDO orderCreateDO) {
        //查询会员等级
        ShopPetrolOrderConfirmVO confirmVO = confirm(orderCreateDO,true);
        String time = DateUtils.dateTimeNow();
        long orderId = 0L;
        try {
            orderId = IdWorker.getFlowIdWorkerInstance().nextId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        orderCreateDO.setId(orderId);
        orderCreateDO.setOrderSn(OrderConstants.SnPrefix.PETROL.getValue() + time + NumberUtils.generateCode(5));
        orderCreateDO.setPaySn(OrderConstants.SnPrefix.PAY_MEMBER.getValue() + time + NumberUtils.generateCode(4));
        orderCreateDO.setProductName(confirmVO.getProductName());
        orderCreateDO.setProductSn(confirmVO.getProductSn());
        orderCreateDO.setProductUnitPrice(confirmVO.getPrice());
        orderCreateDO.setProductQuantity(confirmVO.getProductQuantity());
        orderCreateDO.setOrderCost(confirmVO.getOrderCost());
        orderCreateDO.setPayCost(confirmVO.getPayCost());
        orderCreateDO.setCouponId(confirmVO.getCouponId());
        if (0 == orderCreateDO.getCouponId()) {
            //使用会员折扣
            orderCreateDO.setMemberDiscount(confirmVO.getDiscountAmount());
            orderCreateDO.setCouponDiscount(BigDecimal.ZERO);
        } else {
            orderCreateDO.setMemberDiscount(BigDecimal.ZERO);
            orderCreateDO.setCouponDiscount(confirmVO.getDiscountAmount());
            //TODO:修改优惠券的使用状态
            memberCouponService.useCoupon(orderCreateDO.getMemberId(), orderCreateDO.getCouponId());
        }
        orderCreateDO.setPayWay(confirmVO.getPayWay());
        orderCreateDO.setDiscountType(confirmVO.getDiscountType());
        orderCreateDO.setDiscountTypeDesc(confirmVO.getDiscountTypeDesc());
        orderCreateDO.setDiscountTitle(confirmVO.getDiscountTitle());
        orderCreateDO.setDiscountAmount(confirmVO.getDiscountAmount());
        orderCreateDO.setOrderStatus(OrderConstants.OrderStatusEnum.PRE_PAY.getValue());
        orderCreateDO.setPayStatus(OrderConstants.OrderPayStatusEnum.PRE_PAY.getValue());
        if (null != confirmVO.getProductAttrId()) {
            orderCreateDO.setProductAttrId(confirmVO.getProductAttrId());
            orderCreateDO.setProductAttrName(confirmVO.getProductAttrName());
        }
        orderCreateDO.setPayTime(null);
        orderCreateDO.setCreateTime(new Date());
        orderCreateDO.setCreateBy("小程序下单");
        //TODO:查看是否送积分
        Long vipTypeId = memberMapper.getMemberVipIdById(orderCreateDO.getMemberId());
        MemberVipBenefitVO benefitInfo = memberVipBenefitMapper.getBenefitInfoByProductId(vipTypeId, orderCreateDO.getShopId(), orderCreateDO.getProductId());
        if (1 == benefitInfo.getIsCredit()) {
            if (null != benefitInfo.getBenefitCredit() && benefitInfo.getBenefitCredit() > 0) {
                orderCreateDO.setGiftCredit(benefitInfo.getBenefitCredit());
            } else if (null != benefitInfo.getBenefitCreditRate() && BigDecimal.ZERO.compareTo(benefitInfo.getBenefitCreditRate()) < 0) {
                orderCreateDO.setGiftCredit(orderCreateDO.getPayCost().multiply(benefitInfo.getBenefitCreditRate()).toBigInteger().intValue());
            }
        }
        shopPetrolOrderMapper.insertSelective(orderCreateDO);
        return orderCreateDO.getOrderSn();
    }


    @Override
    public ShopPetrolOrderConfirmVO confirm(ShopPetrolOrderDO shopPetrolOrderDO,boolean isOrder) {
        Date nowDate = new Date();
        //查询会员等级
        MemberVO memberInfo = memberMapper.getProfileById(shopPetrolOrderDO.getMemberId());
        if (null == memberInfo) {
            throw new BusinessException("请先授权登录！");
        }
        ShopPetrolOrderConfirmVO shopPetrolOrderConfirmVO = new ShopPetrolOrderConfirmVO();
        List<ShopProductConfigDO> configList = shopProductConfigMapper.getConfigListByGroup("pay.switch", shopPetrolOrderDO.getShopId(), shopPetrolOrderDO.getProductId());
        shopPetrolOrderConfirmVO.setIsWxPay(1);
        shopPetrolOrderConfirmVO.setIsBalancePay(1);
        shopPetrolOrderConfirmVO.setIsOfflinePay(1);
        shopPetrolOrderConfirmVO.setPayWay(shopPetrolOrderDO.getPayWay());
        shopPetrolOrderConfirmVO.setProductId(shopPetrolOrderDO.getProductId());
        shopPetrolOrderConfirmVO.setProductAttrId(0L);
        shopPetrolOrderConfirmVO.setProductAttrName("");
        if (!configList.isEmpty()) {
            configList.forEach(x -> {
                if (x.getProductId().equals(shopPetrolOrderDO.getProductId())) {
                    if (x.getConfigFlag().equals("wx")) {
                        shopPetrolOrderConfirmVO.setIsWxPay(Integer.parseInt(x.getConfigValue()));
                    }
                    if (x.getConfigFlag().equals("balance")) {
                        shopPetrolOrderConfirmVO.setIsBalancePay(Integer.parseInt(x.getConfigValue()));
                    }
                    if (x.getConfigFlag().equals("offline")) {
                        shopPetrolOrderConfirmVO.setIsOfflinePay(Integer.parseInt(x.getConfigValue()));
                    }
                }
            });
        }
        if (shopPetrolOrderConfirmVO.getIsWxPay() == 0
                && shopPetrolOrderConfirmVO.getIsOfflinePay() == 0
                && shopPetrolOrderConfirmVO.getIsBalancePay() == 0) {
            throw new BusinessException("暂无可用的支付方式，请联系油站人员！");
        }
        if(isOrder){
            if (shopPetrolOrderConfirmVO.getIsBalancePay() == 0 &&
                    shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue()) {
                throw new BusinessException("不支持余额支付！");
            } else if (shopPetrolOrderConfirmVO.getIsWxPay() == 0 &&
                    shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.WX_PAY.getValue()){
                throw new BusinessException("不支持微信支付！");
            } else if(shopPetrolOrderConfirmVO.getIsOfflinePay() == 0 &&
                    shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue()){
                throw new BusinessException("不支持线下支付！");
            }
        }
        if (null == shopPetrolOrderConfirmVO.getPayWay()) {
            //确认订单，无选择支付方式，默认选一个可以使用的
            if (shopPetrolOrderConfirmVO.getIsBalancePay() == 1) {
                shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue());
            } else if (shopPetrolOrderConfirmVO.getIsWxPay() == 1) {
                shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.WX_PAY.getValue());
            } else{
                shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue());
            }
        }

        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setIsEnable(1);
        searchVO.setIsDelete(0);
        searchVO.setMemberVipTypeId(memberInfo.getVipTypeId());
        searchVO.setShopId(shopPetrolOrderDO.getShopId());
        searchVO.setProductId(shopPetrolOrderDO.getProductId());
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
        PetrolProductVO productInfo = productMapper.getPetrolProductDetail(searchVO);
        //2023-03-05 独享则扣
//        BigDecimal benefitDiscountRate = memberVipBenefitExtMapper.getBenefitDiscountRate(shopPetrolOrderDO.getMemberId(),shopPetrolOrderDO.getProductId());
        BigDecimal benefitDiscountRate = null;
        if(null != benefitDiscountRate){
            productInfo.setBenefitDiscountRate(benefitDiscountRate);
        }
        if (null == productInfo || 0 == productInfo.getStock()) {
            throw new BusinessException("该油号暂不提供一键加油");
        }
        if (null != shopPetrolOrderDO.getProductAttrId() && 0 != shopPetrolOrderDO.getProductAttrId()) {
            String productAttrName = shopProductAttributeMapper.getAttrName(shopPetrolOrderDO.getProductAttrId(), shopPetrolOrderDO.getShopId(), shopPetrolOrderDO.getProductId());
            if (null == productAttrName) {
                throw new BusinessException("所选油枪号未启用，请刷新后重试");
            }
            shopPetrolOrderConfirmVO.setProductAttrId(shopPetrolOrderDO.getProductAttrId());
            shopPetrolOrderConfirmVO.setProductAttrName(productAttrName);
        }
        //默认没有折扣优惠
        shopPetrolOrderConfirmVO.setIsDiscount(0);
//        if (SysConfigConstants.DIESEL_OIL_PRODUCT_SN.equals(productInfo.getProductSn())) {
//            //柴油特有标识
//            //柴油加油有折扣优惠+优惠券
//            shopPetrolOrderConfirmVO.setIsDiscount(1);
//            //默认只可以微信支付
//            shopPetrolOrderConfirmVO.setIsBalancePay(0);
//            if (shopPetrolOrderConfirmVO.getIsWxPay() == 0 && shopPetrolOrderConfirmVO.getIsOfflinePay() == 0) {
//                throw new BusinessException("暂无可用的支付方式，请联系油站人员！");
//            }
//            if(shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue()){
//                if(shopPetrolOrderConfirmVO.getIsWxPay() == 1){
//                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.WX_PAY.getValue());
//                }else if(shopPetrolOrderConfirmVO.getIsOfflinePay() == 1){
//                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue());
//                }
//            }else{
//                //判断是否开关关闭了，关闭了自动选择其他
//                if(shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.WX_PAY.getValue()) {
//                    if(shopPetrolOrderConfirmVO.getIsWxPay() == 1){
//                        shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.WX_PAY.getValue());
//                    }else{
//                        shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue());
//                    }
//                }else{
//                    if(shopPetrolOrderConfirmVO.getIsOfflinePay() == 1){
//                        shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue());
//                    }else{
//                        shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.WX_PAY.getValue());
//                    }
//                }
//            }
//        } else {
            //查询会员余额
            MemberDO memberAsset = memberMapper.getAssetById(shopPetrolOrderDO.getMemberId());
            shopPetrolOrderConfirmVO.setMemberBalance(memberAsset.getBalance());
            //判断是否开关关闭了，关闭了自动选择其他
            if(shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.WX_PAY.getValue()) {
                if(shopPetrolOrderConfirmVO.getIsWxPay() == 1){
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.WX_PAY.getValue());
                }else if(shopPetrolOrderConfirmVO.getIsBalancePay() == 1){
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue());
                }else{
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue());
                }
            }else if(shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue()){
                if(shopPetrolOrderConfirmVO.getIsBalancePay() == 1){
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue());
                }else if(shopPetrolOrderConfirmVO.getIsWxPay() == 1){
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.WX_PAY.getValue());
                }else{
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue());
                }
            }else{
                if(shopPetrolOrderConfirmVO.getIsOfflinePay() == 1){
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue());
                }else if(shopPetrolOrderConfirmVO.getIsBalancePay() == 1){
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue());
                }else{
                    shopPetrolOrderConfirmVO.setPayWay(OrderConstants.OrderPayWayEnum.WX_PAY.getValue());
                }
            }
//            if (shopPetrolOrderConfirmVO.getPayWay() == OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue()) {
//                //汽油余额支付享受折扣优惠
//                shopPetrolOrderConfirmVO.setIsDiscount(1);
//            }
//        }
        shopPetrolOrderConfirmVO.setProductSn(productInfo.getProductSn());
        shopPetrolOrderConfirmVO.setProductName(productInfo.getProductName() + productInfo.getProductCategoryName());
        shopPetrolOrderConfirmVO.setProductQuantity(shopPetrolOrderDO.getOrderCost().divide(productInfo.getPrice(), 2, RoundingMode.HALF_UP));
        shopPetrolOrderConfirmVO.setBuyUnit(productInfo.getBuyUnit());
        shopPetrolOrderConfirmVO.setOrderCost(shopPetrolOrderDO.getOrderCost());
        shopPetrolOrderConfirmVO.setPrice(productInfo.getPrice());
        List<PetrolDiscountBO> petrolDiscountList = new ArrayList<>();
        shopPetrolOrderConfirmVO.setDiscountAmount(BigDecimal.ZERO);
        shopPetrolOrderConfirmVO.setDiscountTitle("暂无可使用优惠");
        //TODO:查询会员折扣
//        if (1 == productInfo.getIsDiscount() && 1 == productInfo.getIsBenefitEnable() && 1 == shopPetrolOrderConfirmVO.getIsDiscount()) {
//            PetrolDiscountBO memberDiscountInfo = new PetrolDiscountBO();
//            memberDiscountInfo.setCouponId(0L);
//            memberDiscountInfo.setIsSelect(0);
//            memberDiscountInfo.setIsEnable(1);
//            memberDiscountInfo.setReachAmount(BigDecimal.ZERO);
//            memberDiscountInfo.setReachAmountDesc("无使用门槛");
//            memberDiscountInfo.setDiscountType(CouponConstants.TypeEnum.MEMBER_DISCOUNT.getValue());
//            memberDiscountInfo.setDiscountTypeDesc("会员折扣卡");
//            memberDiscountInfo.setDisCountAmountDesc(productInfo.getBenefitDiscountRate().multiply(BigDecimal.valueOf(10)).setScale(1, BigDecimal.ROUND_HALF_UP).toString() + "折");
//            memberDiscountInfo.setDisCountAmount(shopPetrolOrderDO.getOrderCost().multiply(BigDecimal.ONE.subtract(productInfo.getBenefitDiscountRate())).setScale(2, BigDecimal.ROUND_HALF_UP));
//            if(null != benefitDiscountRate){
//                memberDiscountInfo.setDiscountRate(benefitDiscountRate);
//                memberDiscountInfo.setDiscountTitle("VIP会员独享" + "加" + productInfo.getProductName() + productInfo.getProductCategoryName() + "享" + memberDiscountInfo.getDisCountAmountDesc());
//            }else{
//                memberDiscountInfo.setDiscountRate(productInfo.getBenefitDiscountRate());
//                memberDiscountInfo.setDiscountTitle(memberInfo.getVipTypeName() + "加" + productInfo.getProductName() + productInfo.getProductCategoryName() + "享" + memberDiscountInfo.getDisCountAmountDesc());
//            }
//            if(memberDiscountInfo.getDiscountRate().compareTo(BigDecimal.ONE)<0){
//                petrolDiscountList.add(memberDiscountInfo);
//            }
//        }
//        if (1 == shopPetrolOrderConfirmVO.getIsDiscount()) {
//            //TODO:查询优惠券
//            MemberCouponSearchVO couponSearchVO = new MemberCouponSearchVO();
//            couponSearchVO.setMemberId(shopPetrolOrderDO.getMemberId());
//            couponSearchVO.setMemberCouponStatus(CouponConstants.MemberCouponStatusEnum.NOT_USE.getValue());
//            couponSearchVO.setModuleType(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
//            couponSearchVO.setIsEnable(1);
//            couponSearchVO.setIsDelete(0);
//            couponSearchVO.setIsDelete(0);
//            couponSearchVO.setProductId(shopPetrolOrderDO.getProductId());
//            List<MemberCouponVO> memberCouponList = memberCouponService.searchList(couponSearchVO);
//            //TODO:判断优惠券是否可用
//            if (!memberCouponList.isEmpty()) {
//                PetrolDiscountBO couponInfo;
//                for (MemberCouponVO one : memberCouponList
//                ) {
//                    couponInfo = new PetrolDiscountBO();
//                    couponInfo.setDiscountTitle(one.getTitle());
//                    couponInfo.setCouponId(one.getCouponId());
//                    couponInfo.setIsEnable(1);
//                    couponInfo.setIsSelect(0);
//                    couponInfo.setReachAmount(one.getReachAmount());
//                    if (BigDecimal.ZERO.compareTo(one.getReachAmount()) == 0) {
//                        couponInfo.setReachAmountDesc("无使用门槛");
//                    } else {
//                        if (shopPetrolOrderDO.getOrderCost().compareTo(one.getReachAmount()) < 0) {
//                            //不到门槛金额
//                            couponInfo.setIsEnable(0);
//                        }
//                        couponInfo.setReachAmountDesc("满" + one.getReachAmount() + "元可用");
//                    }
//                    if (CouponConstants.TypeEnum.FACE_VALUE.getValue() == one.getCouponType()) {
//                        if (shopPetrolOrderDO.getOrderCost().compareTo(BigDecimal.valueOf(one.getFaceValue())) < 0) {
//                            couponInfo.setIsEnable(0);
//                        }
//                    }
//                    couponInfo.setDiscountType(one.getCouponType());
//                    couponInfo.setDiscountTypeDesc(CouponConstants.TypeEnum.match(one.getCouponType()).getDesc() + "券");
//                    if (CouponConstants.TypeEnum.FACE_VALUE.getValue() == one.getCouponType()) {
//                        couponInfo.setDisCountAmount(BigDecimal.valueOf(one.getFaceValue()));
////                    couponInfo.setDisCountAmountDesc("￥" + one.getFaceValue());
//                    } else {
//                        couponInfo.setDiscountRate(one.getDiscount());
//                        couponInfo.setDisCountAmount(shopPetrolOrderDO.getOrderCost().multiply(BigDecimal.ONE.subtract(one.getDiscount())).setScale(2, BigDecimal.ROUND_HALF_UP));
////                    couponInfo.setDisCountAmountDesc(one.getDiscount().multiply(BigDecimal.valueOf(10)).setScale(1, BigDecimal.ROUND_HALF_UP).toString() + "折");
//                    }
//                    couponInfo.setUseStartTime(one.getUseStartTime());
//                    couponInfo.setUseEndTime(one.getUseEndTime());
//                    if (1 == couponInfo.getIsEnable()) {
//                        if (couponInfo.getUseStartTime().getTime() > nowDate.getTime() || couponInfo.getUseEndTime().getTime() < nowDate.getTime()) {
//                            couponInfo.setIsEnable(0);
//                        }
//                    }
//                    if (1 == couponInfo.getIsEnable()) {
//                        petrolDiscountList.add(couponInfo);
//                    }
//                }
//            }
//            if(petrolDiscountList.size()>0){
//                //TODO:优惠券排序1
//                petrolDiscountList.sort((o1, o2) -> {
//                    BigDecimal diff = o1.getDisCountAmount().subtract(o2.getDisCountAmount());
//                    if (diff.compareTo(BigDecimal.ZERO) > 0) {
//                        return -1;
//                    } else {
//                        return 1;
//                    }
//                });
//            }
//        }
//        for (PetrolDiscountBO one : petrolDiscountList
//        ) {
//            if (0 == one.getIsEnable()) {
//                continue;
//            }
//            if (null == shopPetrolOrderDO.getCouponId() || one.getCouponId().equals(shopPetrolOrderDO.getCouponId())) {
//                //无选择优惠，自动选择最优
//                one.setIsSelect(1);
//                shopPetrolOrderConfirmVO.setCouponId(one.getCouponId());
//                shopPetrolOrderConfirmVO.setDiscountAmount(one.getDisCountAmount());
//                shopPetrolOrderConfirmVO.setDiscountTitle(one.getDiscountTitle());
//                shopPetrolOrderConfirmVO.setDiscountType(one.getDiscountType());
//                shopPetrolOrderConfirmVO.setDiscountTypeDesc(one.getDiscountTypeDesc());
//                break;
//            }
//        }
        if (null == shopPetrolOrderConfirmVO.getCouponId()) {
            shopPetrolOrderConfirmVO.setCouponId(0L);
        }
        shopPetrolOrderConfirmVO.setDiscountList(petrolDiscountList);
        shopPetrolOrderConfirmVO.setDiscountCount(petrolDiscountList.size());
        shopPetrolOrderConfirmVO.setPayCost(shopPetrolOrderDO.getOrderCost().subtract(shopPetrolOrderConfirmVO.getDiscountAmount()));
        if (shopPetrolOrderConfirmVO.getPayCost().compareTo(BigDecimal.ZERO) == 0) {
            shopPetrolOrderConfirmVO.setPayCost(BigDecimal.valueOf(0.01));
            shopPetrolOrderConfirmVO.setDiscountAmount(shopPetrolOrderConfirmVO.getDiscountAmount().subtract(BigDecimal.valueOf(0.01)));
        }
        return shopPetrolOrderConfirmVO;
    }

    @Override
    public PayVO getPayInfo(String orderSn) {
        return shopPetrolOrderMapper.getPayInfo(orderSn);
    }

    @Override
    @Transactional
    public void deleteByMemberId(Long memberId) {
        Example example = new Example(ShopPetrolOrderDO.class);
        example.createCriteria().andEqualTo("memberId", memberId)
                .andEqualTo("orderStatus", OrderConstants.OrderStatusEnum.PRE_PAY.getValue())
                .andEqualTo("payStatus", OrderConstants.OrderPayStatusEnum.PRE_PAY.getValue());
        List<ShopPetrolOrderDO> orderList = shopPetrolOrderMapper.selectByExample(example);
        if (!orderList.isEmpty()) {
            for (ShopPetrolOrderDO one : orderList
            ) {
                if (one.getCouponId() > 0) {
                    //TODO:优惠券回滚
                    memberCouponService.rollBack(one.getMemberId(), one.getCouponId());
                }
                //TODO：删除订单
                shopPetrolOrderMapper.delete(one);
            }
        }
    }

    @Override
    public ShopPetrolOrderDO getDetail(ShopOrderSearchVO shopOrderSearchVO) {
        shopOrderSearchVO.setIsDelete(0);
        ShopPetrolOrderDO orderInfo = shopPetrolOrderMapper.getDetail(shopOrderSearchVO);
        if (orderInfo == null) {
            throw new BusinessException("订单不存在！");
        }
        return orderInfo;
    }

    @Override
    @Synchronized
    @Transactional(propagation = REQUIRES_NEW)
    public void payNotifyHandle(Map<String, String> notifyMap) {
        BigDecimal payCost;
        String time = DateUtils.dateTimeNow();
        int payWay = OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue();
        HashMap<String, String> orderNotifyParam = new HashMap<>();//充值订单消息通知
        HashMap<String, String> balanceNotifyParam = new HashMap<>();//余额变动消息通知
        if (notifyMap.containsKey("balanceAmount")) {
            Long memberId = Long.valueOf(notifyMap.get("memberId"));
            Long shopId = Long.valueOf(notifyMap.get("shopId"));
            payCost = new BigDecimal(notifyMap.get("balanceAmount"));
            MemberDO memberAsset = memberMapper.getAssetById(memberId);
            //TODO:判断是否有足够的余额
            if (memberAsset.getBalance().compareTo(payCost) < 0) {
                throw new BusinessException("余额不足，请充值！");
            }
            BigDecimal newBalance = memberAsset.getBalance().subtract(payCost);
            //TODO:修改会员余额
            MemberDO memberUpdate = new MemberDO();
            memberUpdate.setId(memberId);
            memberUpdate.setBalance(newBalance);
            memberMapper.updateByPrimaryKeySelective(memberUpdate);
            //TODO:余额变动记录
            MemberBalanceRecordDO memberBalanceRecordDO = new MemberBalanceRecordDO();
            memberBalanceRecordDO.setShopId(shopId);
            memberBalanceRecordDO.setRecordSn(OrderConstants.SnPrefix.BALANCE_MEMBER.getValue() + DateUtils.dateTimeNow() + NumberUtils.generateCode(4));
            memberBalanceRecordDO.setType(MemberRechargeConstants.TypeEnum.SYSTEM_INSERT.getValue());
            memberBalanceRecordDO.setChangeType(MemberRechargeConstants.ChangeTypeEnum.DECREASE.getValue());
            memberBalanceRecordDO.setLinkModel(MemberRechargeConstants.LinkModelEnum.PAY.getValue());
            memberBalanceRecordDO.setLinkSn(notifyMap.get("paySn"));
            memberBalanceRecordDO.setMemberId(memberId);
            memberBalanceRecordDO.setOldBalance(memberAsset.getBalance());
            memberBalanceRecordDO.setChangeBalance(payCost.negate());
            memberBalanceRecordDO.setCreateBy("会员一键加油");
            memberBalanceRecordDO.setCreateTime(new Date());
            memberBalanceRecordDO.setNewBalance(newBalance);
            memberBalanceRecordDO.setRemark("余额支付成功,支付扣除:" + payCost + "元"
                    + "，帐号余额：" + newBalance + "元"
                    + "，支付单号：" + notifyMap.get("paySn"));
            memberBalanceRecordMapper.insertSelective(memberBalanceRecordDO);
            //余额变动-消息通知
            balanceNotifyParam.put("isInfo", "Y");
            balanceNotifyParam.put("templateKey", "balanceChange");
            balanceNotifyParam.put("shopId", memberBalanceRecordDO.getShopId().toString());
            balanceNotifyParam.put("linkModelDesc", MemberRechargeConstants.LinkModelEnum.PAY.getValueDesc());
            balanceNotifyParam.put("linkSn", memberBalanceRecordDO.getLinkSn());
            balanceNotifyParam.put("changeBalance", memberBalanceRecordDO.getChangeBalance().toString());
            balanceNotifyParam.put("newBalance", memberBalanceRecordDO.getNewBalance().toString());
            balanceNotifyParam.put("createTime", DateUtils.getTime());
            balanceNotifyParam.put("balanceChangeRemark", memberBalanceRecordDO.getRemark());
        } else if (notifyMap.containsKey("wxAmount")) {
            payCost = new BigDecimal(notifyMap.get("wxAmount"));
            payCost = payCost.divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            payWay = OrderConstants.OrderPayWayEnum.WX_PAY.getValue();
        } else if (notifyMap.containsKey("offlinePayAmount")) {
            payCost = new BigDecimal(notifyMap.get("offlinePayAmount"));
            payWay = OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue();
        } else {
            throw new BusinessException("没有此订单！");
        }
        ShopPetrolOrderDO orderInfo = shopPetrolOrderMapper.getDetailByPaySn(notifyMap.get("paySn"));
        if (null == orderInfo) {
            throw new BusinessException("没有此订单！");
        }
        if (orderInfo.getPayStatus() != OrderConstants.OrderPayStatusEnum.PRE_PAY.getValue()) {
            throw new BusinessException("订单已支付！");
        }
        if (!orderInfo.getPayCost().equals(payCost)) {
            throw new BusinessException("订单异常！");
        }
        //TODO：累计消费
        MemberDO memberAsset = memberMapper.getAssetById(orderInfo.getMemberId());
        MemberDO memberUpdate = new MemberDO();
        memberUpdate.setId(orderInfo.getMemberId());
        memberUpdate.setLastConsumeTime(new Date());
        memberUpdate.setShopId(orderInfo.getShopId());
        if (OrderConstants.OrderPayWayEnum.WX_PAY.getValue() == payWay ||
                OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue() == payWay) {
            //微信支付，累计消费金额
            BigDecimal newTotalPetrolAmount = memberAsset.getTotalPetrolAmount().add(orderInfo.getPayCost());
            memberUpdate.setTotalPetrolAmount(newTotalPetrolAmount);
        }
        //TODO：商品销量和库存变更
        productMapper.stockSubtraction(orderInfo.getProductId());
        productMapper.saleIncrement(orderInfo.getProductId());
        productMapper.shopSaleIncrement(orderInfo.getShopId(), orderInfo.getProductId());
        //TODO:查看是否赠送积分
        boolean isCredit = false;
        if (SysConfigConstants.DIESEL_OIL_PRODUCT_SN.equals(orderInfo.getProductSn())) {
            //柴油只能微信支付，所以肯定送积分
            isCredit = true;
        } else if (payWay == OrderConstants.OrderPayWayEnum.WX_PAY.getValue()) {
            isCredit = true;
        }
        //汽油只有微信支付才送积分
        if (isCredit && orderInfo.getGiftCredit() > 0) {
            Integer newCredit = memberAsset.getCredit() + orderInfo.getGiftCredit();
            //TODO:修改会员余额、累计充值金额、积分
            memberUpdate.setCredit(newCredit);

            MemberCreditRecordDO memberCreditRecordDO = new MemberCreditRecordDO();
            memberCreditRecordDO.setShopId(orderInfo.getShopId());
            memberCreditRecordDO.setRecordSn(OrderConstants.SnPrefix.CREDIT_MEMBER.getValue() + time + NumberUtils.generateCode(4));
            memberCreditRecordDO.setType(MemberCreditConstants.TypeEnum.SYSTEM_INSERT.getValue());
            memberCreditRecordDO.setChangeType(MemberCreditConstants.ChangeTypeEnum.INCREASE.getValue());
            memberCreditRecordDO.setLinkModel(MemberCreditConstants.LinkModelEnum.PETROL.getValue());
            memberCreditRecordDO.setLinkSn(orderInfo.getOrderSn());
            memberCreditRecordDO.setMemberId(orderInfo.getMemberId());
            memberCreditRecordDO.setOldCredit(memberAsset.getCredit());
            memberCreditRecordDO.setChangeCredit(orderInfo.getGiftCredit());
            memberCreditRecordDO.setNewCredit(newCredit);
            memberCreditRecordDO.setRemark("加油赠送积分,加油实付:" + orderInfo.getPayCost() + "元"
                    + "，赠送：" + orderInfo.getGiftCredit() + "分"
                    + "，加油单号：" + orderInfo.getOrderSn());
            memberCreditRecordDO.setCreateBy("会员加油赠送积分");
            memberCreditRecordDO.setCreateTime(new Date());
            memberCreditRecordMapper.insertSelective(memberCreditRecordDO);
            orderNotifyParam.put("creditRemark", "加油赠送" + orderInfo.getGiftCredit() + "积分");
        } else {
            //赠送积分设置为0
            shopPetrolOrderMapper.resetGiftCredit(orderInfo.getId());
        }
        //消息通知
        orderNotifyParam.put("isInfo", "Y");
        orderNotifyParam.put("templateKey", "petrol");
        orderNotifyParam.put("shopId", orderInfo.getShopId().toString());
        ShopVO shopInfo = shopMapper.getShopGeneralInfo(orderInfo.getShopId());
        orderNotifyParam.put("shopName", shopInfo.getShopName());
        orderNotifyParam.put("orderStatusDesc", "支付成功");
        orderNotifyParam.put("payCost", payCost.toString() + "元");
        orderNotifyParam.put("payTime", DateUtils.getTime());
        orderNotifyParam.put("orderSn", orderInfo.getOrderSn());
        orderNotifyParam.put("openid", memberAsset.getOpenid());
        memberMapper.updateByPrimaryKeySelective(memberUpdate);
        shopPetrolOrderMapper.paySuccessHandle(orderInfo.getId(), payWay);
        //微信模板通知
        AsyncManager.me().execute(ApiAsyncFactory.sendWechatTemplateNotify(orderNotifyParam));
        if (balanceNotifyParam.containsKey("balanceChangeRemark")) {
            balanceNotifyParam.put("openid", memberAsset.getOpenid());
            AsyncManager.me().execute(ApiAsyncFactory.sendWechatTemplateNotify(balanceNotifyParam));
        }
        //短信通知
        HashMap<String, String> smsNotifyParam = new HashMap<>();//余额变动消息通知
        smsNotifyParam.put("shopId", orderInfo.getShopId().toString());
        smsNotifyParam.put("phone", memberAsset.getPhone());
        smsNotifyParam.put("smsVar", DateUtils.getTime() + "," + shopInfo.getShopName() + "," + orderInfo.getPayCost());
        if (balanceNotifyParam.containsKey("balanceChangeRemark")) {
            smsNotifyParam.put("templateKey", "petrolBalance");
            smsNotifyParam.put("smsVar", smsNotifyParam.get("smsVar") + "," + balanceNotifyParam.get("newBalance"));
        } else {
            smsNotifyParam.put("templateKey", "petrolWx");
        }
        if(payWay != OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue()){
            //非线下支付要短信通知
            AsyncManager.me().execute(ApiAsyncFactory.sendSmsNotify(smsNotifyParam));
        }
        //语音通知
        HashMap<String, String> announceNotifyParam = new HashMap<>();
        announceNotifyParam.put("shopId", orderInfo.getShopId().toString());
        announceNotifyParam.put("annSn", "NN" + time + NumberUtils.generateCode(4));
        announceNotifyParam.put("orderSn", orderInfo.getOrderSn());
        if (StringUtils.isNotEmpty(orderInfo.getProductAttrName())) {
            announceNotifyParam.put("annTitle", orderInfo.getProductAttrName() + "收到" + orderInfo.getOrderCost() + "元");
        } else {
            announceNotifyParam.put("annTitle", orderInfo.getProductName().replace("#", "号") + "收到" + orderInfo.getOrderCost() + "元");
        }
        AsyncManager.me().execute(ApiAsyncFactory.sendAnnounceNotify(announceNotifyParam));
    }
}
